#include "HufArc.h"

int copy (FILE* fileToRead,FILE * fileToWrite, unsigned long long int fileSize, unsigned int * ChkSum)
{

int rc = 0;
char * buf = (char *) calloc (SIZE_BUF,sizeof(char));
if (!buf)
	cl_exit (COPY,MEMORY_ERR);

	for (;;)
	{
		if ((fileSize/(SIZE_BUF)) != 0)//Why does SIZE_BUF in brackets? See definition
		{
			rc = fread (buf,sizeof(char),SIZE_BUF,fileToRead);
			if (rc != SIZE_BUF)
			{
				//cl_exit (COPY_EXIT,buf,fileToRead,fileToWrite);
				free (buf);
				return -1;
				/*free (buf);
				fclose (fileToRead);
				fclose (fileToWrite);*//*
				longjmp (errorBuf,READ_ERR);
				return NULL;*/
			}
			if (fileToWrite) {
			strWrite (fileToWrite,buf,SIZE_BUF,ChkSum);
			} else {
				ChkSum[0] += Crc32 (buf,SIZE_BUF);
			}
			fileSize -= SIZE_BUF;
		} else {
			if (fileSize > 0)
			{
				rc = fread (buf,sizeof(char),fileSize,fileToRead);
				if (rc != fileSize)
				{
					//cl_exit (COPY_EXIT,buf,fileToRead,fileToWrite);
					free (buf);
					return -1;
					/*free (buf);
					fclose (fileToRead);
					fclose (fileToWrite);
					longjmp (errorBuf,READ_ERR);
					return NULL;*/
				}
				if (fileToWrite) {
					strWrite (fileToWrite,buf,fileSize,ChkSum);
				} else {
					ChkSum[0] += Crc32 (buf,fileSize);
				}
				break;
			} else {
				break;
			}
		}
	}
	free (buf);
	return 0;
}